package com.shinji.tratu;

import java.io.IOException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class AudioPlayer implements OnCompletionListener, OnErrorListener,
		OnPreparedListener {
	MediaPlayer mp = null;
	private String TAG = "AudioPlayer";
	String dataSource;
	View button;
	Context mContext;

	public String getDataSource() {
		return dataSource;
	}

	public void setDataSource(String dataSource) {
		this.dataSource = dataSource;
	}

	public void setButton(View btn) {
		button = btn;
	}

	public AudioPlayer(Context ctx) {
		mp = new MediaPlayer();
		mp.setOnCompletionListener(this); // Important
		mp.setOnPreparedListener(this);
		mContext = ctx;
	}

	private void displayNetworkError() {
		Toast.makeText(mContext, mContext.getString(R.string.search_error),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onPrepared(MediaPlayer play) {
		Log.i(TAG, "onPrepared");
		play.start();
	}

	@Override
	public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
		Log.e(TAG, "onError");
		button.setEnabled(true);
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		Log.i(TAG, "onCompletion");
		button.setEnabled(true);
		if (mp.isPlaying()) {
			// stopPlayer();
		}
	}

	// public void gogo() {
	// if (mp.isPlaying()) {
	// stopPlayer();
	// }
	// playAudio();
	// }

	public void stopPlayer() {
		if (mp.isPlaying()) {
			mp.stop();
		}
	}

	/**
	 * 
	 * @param cView
	 *            contentView for voicemail
	 * @param msg
	 *            voicemail to play
	 */
	public void playAudio() {
		button.setEnabled(false);
		// Play song
		try {
			mp.reset();
			mp.setDataSource(dataSource);
			mp.prepare();
		} catch (IllegalArgumentException e) {
			button.setEnabled(true);
			displayNetworkError();
			Log.e(TAG, "" + e.toString());
		} catch (IllegalStateException e) {
			button.setEnabled(true);
			displayNetworkError();
			Log.e(TAG, "" + e.toString());
		} catch (IOException e) {
			button.setEnabled(true);
			displayNetworkError();
			Log.e(TAG, "" + e.toString());
		}
	}

	public boolean isPlaying() {
		return mp.isPlaying();
	}
}
